Lab 13

Function Types and Scope

CS211 Lab Policy:

Instructions:

This lab is divided into 2 parts. You only will submit your file for part 2.

Part 1:     Investigate function scope

Copy and paste the MATLAB code below and save it into a file called sam.m.
function sam()

  function mary()
    fprintf('nested function mary was called\n');
  end % nested function mary

  function joe()
    fprintf('nested function joe was called\n');
    mary();
  end % nested function joe

  clc();
  fprintf('primary function sam was called\n');
  mary();
  joe();
end % primary function sam

function mary()
  fprintf('subfunction mary was called\n');
end % subfunction mary

function fred()
  fprintf('subfunction fred was called\n');
  mary();
end % subfunction fred

Perform the following tasks and modifications on this file and examine the results to help you better understand function scope. If there is anything you do not understand, please discuss it with your instructor.

Part 2:     Investigate how functions facilitate the organization of complex code

Save the file Ticktacktoe.m to your CS211 programs folder. Then execute the function to play "Tick Tack Toe".

Now modify the code, as described below, to separate the single function Ticktacktoe into logical sub-tasks (i.e., separate subfunctions). Hopefully, when you are finished with these modifications, you will be able to compare the original version with your new modularized version and come to the conclusion that your modified version is better structured, more "readable", and would be easier to debug and maintain over time.

Note: This "Tick Tack Toe" program is not robust -- it does not check for errors! If you were given the task of making it robust, your amount of code would increase greatly. This is an additional reason why modularizing your code is beneficial for large programs. (Just for fun -- not required, try to make your ticktacktoe program robust!)

Turn-in:

Submit your new, modified ticktacktoe.m file.